package com.kevin.j2eeToolBox.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class InvokeTester {

	public int add(int param1, int param2) {

		return param1 + param2;
	}

	public String echo(String message) {
		return "hello" + message;
	}

	public static void main(String[] args) throws Exception {

		Class<?> clazz1 = Class.forName("com.kevin.j2eeToolBox.reflect.Person");

		Constructor<?> cnstructor = clazz1.getConstructor(String.class,
				int.class);

		Object o = cnstructor.newInstance("kevin", 25);

		Object newObj = InvokeTester.CopyObject(o);

		System.out.println(newObj);

	}

	public static Object CopyObject(Object obj) throws Exception {

		Class<?> type = obj.getClass();
		Object newObj = type.newInstance();

		Field[] fields = type.getDeclaredFields();

		for (Field field : fields) {

			String name = field.getName();

			String getMethodName = "get"
					+ Character.toUpperCase(name.charAt(0)) + name.substring(1);
			String setMethodName = "set"
					+ Character.toUpperCase(name.charAt(0)) + name.substring(1);

			Method getMethod = type.getMethod(getMethodName);
			Method SetMethod = type.getMethod(setMethodName,
					new Class[] { field.getType() });

			Object value = getMethod.invoke(obj);
			SetMethod.invoke(newObj, value);
		}

		return newObj;
	}
}

class Person {

	public Person() {

	}

	public Person(String name, int age) {

		this.setAge(age);
		this.setName(name);
	}

	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return this.getName() + this.getAge();
	}

}
